package team.archai.nexus.boot.tool;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Objects;

/**
 * @ClassName: AESUtil
 * @Description:TODO(AES方式加密 可逆)
 * @author: lishibin
 * @date: 2018年12月10日 上午10:05:41
 */
public class AESUtil {

    /**
     * @Fields AES : TODO(用一句话描述这个变量表示什么)
     */
    public static final String AES = "AES";

    /**
     * @Fields charset : TODO(字符編碼 默认GBK)
     */
    public static final String charset = null;

    /**
     * @Fields keysizeAES : TODO(AES加密size)
     */
    public static final int keySizeAES = 128;

    private static AESUtil instance;

    private AESUtil() {

    }

   /**
   * @program: AESUtil
   * @description: 单例模式
   * @author: lishibin
   * @create: 21:31
   **/
    public static AESUtil getInstance() {
        if (instance == null) {
            synchronized (MD5Utils.class) {
                if (instance == null) {
                    instance = new AESUtil();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        String key = "113#212dsa@";

       String end =  encode("1",key);
        System.out.println(end);
        System.out.println(decode(end,key));
    }

    /**
     * @Title: encode @Description: TODO(对字符串res加入key进行AES加密) @param: @param
     * res @param: @param key @param: @return @return: String @throws
     */
    public static String encode(String res, String key) {
        return keyGeneratorES(res, key, true);
    }

    /**
     * @Title: decode @Description: TODO(对字符串res加上key进行AES解密) @param: @param
     * res @param: @param key @param: @return @return: String @throws
     */
    public static String decode(String res, String key) {
        return keyGeneratorES(res, key, false);
    }

    /**
     * @Title: keyGeneratorES @Description:
     * TODO(使用KeyGenerator双向加密，DES/AES，注意这里转化为字符串的时候是将2进制转为16进制格式的字符串，不是直接转，因为会出错) @param: @param
     * res @param: @param algorithm @param: @param key @param: @param
     * keysize @param: @param isEncode @param: @return @return: String @throws
     */
    private static String keyGeneratorES(String res, String key, boolean isEncode) {
        try {
            KeyGenerator kg = KeyGenerator.getInstance(AESUtil.AES);
            if (AESUtil.keySizeAES == 0) {
                byte[] keyBytes = key.getBytes();
                kg.init(new SecureRandom(keyBytes));
            } else if (key == null) {
                kg.init(AESUtil.keySizeAES);
            } else {
                byte[] keyBytes = key.getBytes();
                kg.init(AESUtil.keySizeAES, new SecureRandom(keyBytes));
            }
            SecretKey sk = kg.generateKey();
            SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), AESUtil.AES);
            Cipher cipher = Cipher.getInstance(AESUtil.AES);
            if (isEncode) {
                cipher.init(Cipher.ENCRYPT_MODE, sks);
                byte[] resBytes = res.getBytes();
                return parseByte2HexStr(cipher.doFinal(resBytes));
            }
            cipher.init(Cipher.DECRYPT_MODE, sks);
            return new String(cipher.doFinal(Objects.requireNonNull(parseHexStr2Byte(res))));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Title: parseByte2HexStr @Description: TODO(将二进制转换成16进制) @param: @param
     * buf @param: @return @return: String @throws
     */
    private static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * @Title: parseHexStr2Byte @Description: TODO(将16进制转换为二进制) @param: @param
     * hexStr @param: @return @return: byte[] @throws
     */
    private static  byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}
